<template>
    <div class="Write">
        <div style=" float: left;text-align: left;width: 50%;">
            <el-tag
                    :key="tag"
                    v-for="tag in dynamicTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                {{tag}}
            </el-tag>
            <el-popover

                    placement="bottom"
                    title="最多添加3个标签"
                    width="300"
                    trigger="click"
                    v-model="tagsModelVisible">

                <div>
                    <div style="height: 50px;color: yellowgreen;">找不到标签？
                        <el-button @click="showAddTags" type="warning" style="float: right">创建</el-button>
                    </div>
                    <el-tag
                            style="margin: 10px"
                            v-for="tag in allTags"
                            :key="tag"
                            :type="info"
                            @click="addTag(tag)"
                            list-type="picture-card"

                    >
                        {{tag}}
                    </el-tag>

                </div>
                <el-button @click="showInput" type="danger" class="button-new-tag" size="small" slot="reference">
                    + 添加标签
                </el-button>


            </el-popover>
            <el-dialog
                    title="创建标签"
                    :visible.sync="dialogVisible"
                    width="30%"
            >
                <span>标签名称</span>
                <el-input placeholder="请输入内容" clearable v-model="newTagName"></el-input>

                <span slot="footer" class="dialog-footer">
                 <el-button @click="dialogVisible = false">取 消</el-button>
                 <el-button type="primary" @click="addTagDetail">确 定</el-button>
                 </span>
            </el-dialog>
        </div>


        <span style="width: 40%">
            <el-button @click="uploadArticle" style="float: right" size="small" type="warning">发布</el-button>
            <el-upload
                    action="123"
                    :before-upload="beforeUploadImg"
            >
              <el-button size="small" type="primary">添加文章标识图</el-button>
            </el-upload>

        </span>

        <div ref="toolbar" id="toolbar" class="toolbar"></div>
        <div ref="text" id="text" class="text" v-html="DetailArticle">
            <!--可使用 min-height 实现编辑区域自动增加高度-->

        </div>

    </div>
</template>

<script>
    import E from "wangeditor";
    import {uploadImages} from "../../assets/js/imgur";
    import {Message, Loading} from 'element-ui';

    export default {
        name: "Write",
        data() {
            return {
                editor: "",
                editorContent: "",
                tileName: null,
                dynamicTags: [],
                inputValue: '',
                tagsModelVisible: false,
                input: '',
                allTags: [],
                dialogVisible: false,
                newTagName: null,
                dialogImageUrl: '',
                dialogVisibleImg: false,
                uploadBgImg:'',
                articleId:null
            };
        },
        computed:{
            DetailArticle(){
                return this.$store.state.DetailArticle
            }
        },
        components: {},
        mounted() {
            this.editor = new E(this.$refs.toolbar, this.$refs.text);
            this.editor.customConfig.onchange = html => {
                this.editorContent = html;
            };
            this.editor.customConfig.pasteTextHandle = content => {
                //支持粘贴
                return content;
            };
            // 配置服务器端地址
            // this.editor.customConfig.uploadImgServer = '/upload'
            this.editor.customConfig.zIndex = 1;
            // editor.customConfig.uploadImgServer = "/upload";
            this.editor.customConfig.uploadImgShowBase64 = true; //图片以base64形式保存
            this.editor.customConfig.uploadImgTimeout = 50000;
            // this.editor.customConfig.debug = location.href.indexOf('wangeditor_debug_mode=1') >
            //自定义上传图片事件
            this.editor.customConfig.customUploadImg = function (files, insert) {
                // files 是 input 中选中的文件列表
                console.log(files)
                // insert 是获取图片 url 后，插入到编辑器的方法
                uploadImages(files).then(
                    res => {
                        res.forEach(
                            item => {
                                debugger
                                let imgurl = item["data"]["data"]["link"];
                                insert(imgurl)
                            }
                        )
                    }
                ).catch(err => {
                    console.log(err)
                });
            }

            this.editor.create();

        },
        methods: {
            showAddTags() {   //添加标签
                this.dialogVisible = true
            },
            // 统一处理res
            handleResponse(res) {
                if (res.data.success) {
                    Message({
                        message: res.data.message,
                        type: 'success',
                        duration: 3 * 1000
                    })
                } else {
                    Message({
                        message: res.data.message,
                        type: 'error',
                        duration: 3 * 1000
                    })
                }

            },
            //上传文章
            uploadArticle() {
                let _this = this
                this.$prompt('文章标题', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',

                }).then(({value}) => {
                    this.tileName = value
                    let nowTime = Date.parse(new Date());

                    if(this.$route.params.articleId){
                        this.articleId=this.$route.params.articleId

                    }


                    this.$API.uploadArticle(
                        {
                            id: this.articleId,
                            content: this.editorContent,
                            author: "zxc",
                            img: this.uploadBgImg,
                            title: value,
                            updateTime: nowTime
                        }
                    ).then(
                        res => {
                            _this.$API.updateArticleTag({
                                tags: _this.dynamicTags,
                                title: _this.tileName,
                                timesTamp: nowTime

                            }).then(res => {
                                _this.handleResponse(res)
                            })
                        }
                    )

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消输入'
                    });
                });


            },
            handleClose(tag) {
                this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
            },
            addTag(name) {


                if (this.dynamicTags.length <= 2) {
                    this.dynamicTags.push(name)
                } else {
                    this.$message({
                        type: 'error',
                        message: '最多3个标签'
                    });
                }
            },
            //像数据库添加标签
            addTagDetail() {
                let _this = this
                this.dialogVisible = false
                this.$API.addTag({name: _this.newTagName}).then(
                    res => {
                        this.handleResponse(res)
                    }
                )

            },
            //初始化标签内容
            initTags() {
                debugger
                this.$API.findaAllTags().then(
                    res => {
                        this.allTags = res.data["data"]

                        // console.log(res.data["data"])
                    }
                )

            },
            showInput() {
                this.initTags()
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisibleImg = true;
            },
            beforeUploadImg(file) {
                let _this=this
                let files=[]
                files.push(file)
                console.log(files)
                uploadImages(files).then(
                    res => {
                        res.forEach(
                            item => {
                                let imgurl = item["data"]["data"]["link"];
                                this.uploadBgImg=imgurl
                                _this.$store.dispatch('changeHeaderBgState', imgurl)

                            }
                        )
                    }
                ).catch(err => {
                    console.log(err)
                });

                return false // 返回false不会自动上传

            }

        }


    };
</script>

<style lang="scss" scoped>
    .Write {
        margin: 5px;

        .toolbar {
            font-size: 1.5rem;
            height: 30px;
        }

        .text {
            margin-top: 10px;
            text-align: left;
            background-color: white;
            height: 600px;


        }

        .el-tag + .el-tag {
            margin-left: 10px;

        }

        .button-new-tag {
            margin-left: 10px;
            height: 32px;
            line-height: 30px;
            padding-top: 0;
            padding-bottom: 0;
        }

        .input-new-tag {
            width: 90px;
            margin-left: 10px;
            vertical-align: bottom;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

    }
</style>
